<template>
  <section class="todoapp">
    <hm-header @AddItem="AddItem"></hm-header>
    <hm-main
      :list="NewList"
      @ItemFlag="ItemFlag"
      @ItemDel="ItemDel"
      @isAll="ChangeAll"
    ></hm-main>
    <hm-footer
      :list="list"
      @DelAll="DelAll"
      :state="state"
      @ChangeState="ChangeState"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "active",
  "#/completed": "completed",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: (JSON.parse(localStorage.getItem("list")).length &&
        JSON.parse(localStorage.getItem("list"))) || [
        { name: "吃饭", id: 1, flag: false },
        { name: "睡觉", id: 2, flag: false },
        { name: "打豆豆", id: 3, flag: false },
      ],
      state: obj[location.hash] || "all",
    };
  },
  methods: {
    ItemFlag(id) {
      this.list.find((item) => item.id === id).flag = !this.list.find(
        (item) => item.id === id
      ).flag;
    },
    ItemDel(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    AddItem(item) {
      this.list.push(item);
    },
    ChangeAll(flag) {
      this.list.forEach((item) => (item.flag = flag));
    },
    DelAll() {
      this.list = this.list.filter((item) => item.flag === false);
    },
    ChangeState(value) {
      this.state = value;
    },
  },
  computed: {
    NewList() {
      if (this.state === "all") return this.list;
      if (this.state === "active")
        return this.list.filter((item) => item.flag === false);
      return this.list.filter((item) => item.flag === true);
    },
  },
  watch: {
    list: {
      deep: true,
      handler(NewArr) {
        localStorage.setItem("list", JSON.stringify(NewArr));
        console.log();
      },
    },
  },
};
</script>

<style></style>
